package com.um.jdy.app.base.manager;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.um.jdy.app.base.entity.dto.AddQrcodeDTO;
import com.um.jdy.common.commons.manager.WxManager;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.shop.entity.dto.QrcodeDTO;
import com.um.jdy.common.shop.entity.po.Keyword;
import com.um.jdy.common.shop.entity.po.Qrcode;
import com.um.jdy.common.shop.entity.vo.KeywordVO;
import com.um.jdy.common.shop.service.KeywordService;
import com.um.jdy.common.shop.service.QrcodeService;
import com.um.springboot.starter.exception.ServiceException;
import com.um.weixin.mini.service.WxMiniUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

import static cn.binarywang.wx.miniapp.constant.WxMaConstants.DEFAULT_ENV_VERSION;

/**
 * 管理类：搜索热门关键词
 */
@Slf4j
@Component
public class QrcodeManager {

    @Autowired
    QrcodeService qrcodeService;

    @Autowired
    WxManager wxManager;

    @Transactional
    public String generateQrcode(AddQrcodeDTO dto){
        Qrcode qrcode = new Qrcode();
        qrcode.setData(dto.getData());
        qrcodeService.save(qrcode);

        String filePath = qrcodeService.getFilePath("export");
        FileUtil.mkdir(filePath);
        log.info("filePath:{}", filePath);
        try {
            File file = wxManager.getMiniService(qrcodeService.getComId()).getQrcodeService()
                    .createWxaCodeUnlimit(qrcode.getShopQrcodeId(), dto.getPage(), filePath, false, DEFAULT_ENV_VERSION, 430, true, null, false);
            return qrcodeService.getDownFilePath(file.getName());
        } catch (WxErrorException e) {
            throw new ServiceException(e.getError().getErrorMsg());
        }
    }

    public String get(String scene){
        Qrcode qrcode = qrcodeService.getEntity(scene);
        return Optional.ofNullable(qrcode).orElseGet(Qrcode::new).getData();
    }

}
